package com.servlet.mysert;

import com.domain.Mysert;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.service.MysertService;
import com.service.impl.MysertServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet("/mysertSelectServlet")
public class MysertSelectServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        MysertService service = new MysertServiceImpl();
        ArrayList<Mysert> fmselect = service.select();
        ObjectMapper mapper = new ObjectMapper();
        StringBuilder data = new StringBuilder();
        if(fmselect.size() < 1) {
            resp.getWriter().write("{\"status\":\"0\",\"message\":\"ok\",\"data\":[]}");
            return;
        }
        for (Mysert mysert : fmselect) {
            // 将对象序列化为json字符串
            String s = mapper.writeValueAsString(mysert);   
            data.append(s);
            data.append(",");
        }
        resp.setContentType("application/json");
        resp.setCharacterEncoding("utf-8");
        data.deleteCharAt(data.length() - 1);
        resp.getWriter().write("{\"status\":\"0\",\"message\":\"ok\",\"data\":["+data+"]}");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
